package com.skyolder.milkbee.web.rest.my;

import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.codahale.metrics.annotation.Timed;
import com.skyolder.milkbee.domain.Card;
import com.skyolder.milkbee.domain.User;
import com.skyolder.milkbee.dto.SimpleResult;
import com.skyolder.milkbee.security.SecurityUtils;
import com.skyolder.milkbee.service.CardService;
import com.skyolder.milkbee.service.UserService;
import com.skyolder.milkbee.web.rest.util.PaginationUtil;

import io.swagger.annotations.ApiParam;

/**
 * REST controller for managing Card.
 */
@RestController("myCardResource")
@RequestMapping("/api/my")
public class CardResource {

	private final Logger log = LoggerFactory.getLogger(CardResource.class);
	@Inject
	private CardService cardService;
	@Inject
	private UserService userService;


	@GetMapping("/card")
	@Timed
	public ResponseEntity<List<Card>> getMycards(@ApiParam Pageable pageable) throws URISyntaxException {
		Optional<User> ouser = userService.getUserWithAuthoritiesByLogin(SecurityUtils.getCurrentUserLogin());
		User user = ouser.get();
		Long uid = user.getId();
		Page<Card> page = cardService.findByUserId(uid, pageable);
		HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/mycard");
		return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
	}


	@PutMapping("/card/applyessence/{id}")
	@Timed
	public ResponseEntity<SimpleResult> applyEssence(@PathVariable Long id) throws URISyntaxException {
		SimpleResult sr = new SimpleResult();
		Card one = cardService.findOne(id);
		if (one == null) {
			sr.setSuccess(false);
			return new ResponseEntity<>(sr, HttpStatus.NOT_FOUND);
		}
		Integer essence = one.getEssence();
		if (essence != 0) {
			sr.setSuccess(false);
			return new ResponseEntity<>(sr, HttpStatus.FORBIDDEN);
		}
		Optional<User> ouser = userService.getUserWithAuthoritiesByLogin(SecurityUtils.getCurrentUserLogin());
		User user = ouser.get();
		Long uid = user.getId();
		if(one.getUserId()!=uid){
			return new ResponseEntity<>(sr, HttpStatus.FORBIDDEN);
		}
		one.setEssence(2);
		cardService.save(one);
		sr.setSuccess(true);
		return new ResponseEntity<>(sr, HttpStatus.OK);
	}
}
